package com.glqiang.filter;

import com.glqiang.enums.ResultEnum;
import com.glqiang.security.CustomAuthenticationToken;
import com.glqiang.security.CustomUserDetails;
import com.glqiang.util.JwtUtils;
import com.glqiang.util.RedisCache;
import com.glqiang.util.ServletUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * 自定义jwt过滤器
 *
 * @author glq1218
 */
@Component
public class CustomOncePerRequestFilter extends OncePerRequestFilter {
    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull FilterChain filterChain) throws ServletException, IOException {
        if ("/login".equals(request.getRequestURI())) {
            filterChain.doFilter(request, response);
            return;
        }
        // 获取token
        String token = request.getHeader("Authorization");
        if (!StringUtils.hasText(token)) {
            filterChain.doFilter(request, response);
            return;
        }
        // 解析token获取用户名
        String username = JwtUtils.getUsername(token);
        if (!StringUtils.hasText(username)) {
            ServletUtils.renderString(response, ResultEnum.NO_TOKEN);
            // throw new CustomException(ResultEnum.NO_TOKEN);
            return;
        }
        // 通过username获取存在redis中的用户信息
        CustomUserDetails userDetails = redisCache.getCacheObject("loginUser:" + username);
        if (Objects.isNull(userDetails)) {
            ServletUtils.renderString(response, ResultEnum.NO_LOGIN);
            // throw new CustomException(ResultEnum.NO_LOGIN);
            return;
        }
        // 生成认证Token存入SecurityContext
        CustomAuthenticationToken customAuthenticationToken
                = new CustomAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(customAuthenticationToken);
        filterChain.doFilter(request, response);
    }
}
